package com.atguigu.cloud.controller;

import com.atguigu.cloud.entities.PayDTO;
import com.atguigu.cloud.resp.ResultData;
import jakarta.annotation.Resource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

//一般情况下，通过浏览器的地址栏输入url，发送的只能是get请求
//     * 我们模拟消费者发送get请求，but底层调用post方法，客户端消费者参数PayDTO可以不添加@RequestBody

@RestController
public class OrderController {
//    public static final String PaymentSrv_URL = "http://localhost:8001";

    public static final String PaymentSrv_URL = "http://cloud-payment-service";//服务注册中心上的微服务名称
    @Resource
    private RestTemplate restTemplate;

    @GetMapping(value = "/consumer/pay/add")
    public ResultData addOrder(PayDTO payDTO){
        return restTemplate.postForObject(PaymentSrv_URL + "/pay/add", payDTO, ResultData.class);
    }

    @GetMapping(value = "/consumer/pay/get/{id}")
    public ResultData getOrder(@PathVariable("id") String id){
        return restTemplate.getForObject(PaymentSrv_URL + "/pay/get/"+id, ResultData.class);
    }


    @DeleteMapping(value = "/consumer/pay/delete/{id}")
    public ResultData deleteOrder(@PathVariable("id") String id){
        return restTemplate.exchange(
                PaymentSrv_URL + "/pay/del/" + id,
                HttpMethod.DELETE,
                null,
                ResultData.class
        ).getBody();
    }

    @PostMapping(value = "/consumer/pay/update")
    public ResultData updateOrder(@RequestBody PayDTO payDTO){
        HttpEntity<PayDTO> requestEntity = new HttpEntity<>(payDTO);
        return restTemplate.exchange(PaymentSrv_URL + "/pay/update",HttpMethod.PUT, requestEntity, ResultData.class).getBody();
    }

    //测试负载均衡的接口
    @GetMapping(value = "/consumer/pay/get/info")
    public String getInfoByConsul() {
        return restTemplate.getForObject(PaymentSrv_URL + "/pay/get/info", String.class);
    }
}
